<?php
/**
 * Created by PhpStorm.
 * User: suruixiang
 * Date: 2017/10/9
 * Time: 上午10:27
 */
namespace app\index\model;

use think\image\Exception;
use think\Model;
use think\Request;
use think\Config;
use think\Session;

class User extends Model
{
    /**
     * 跳转授权
     */
    public function tuAuth()
    {
        $appid = Config::get('config.appid');
        $redirect_uri = urlencode(Request::instance()->domain() . '/index/login/dologin');
        $redirect_uri = urlencode('http://cps.chenzao.com/index/login/dologin');
        $auth_url = "https://open.weixin.qq.com/connect/qrconnect?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
        //header("Location: {$auth_url}");
        echo "<script>location.href='{$auth_url}'</script>";
    }

    /**
     * 微信登录授权
     * @link https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=f114fb1e60a052c991908308630f42ad25a3ed40&lang=zh_CN
     * @return array
     */
    private function wechatAuth()
    {
        $code = Request::instance()->param('code');
        $appid = Config::get('config.appid');
        $appsecret = Config::get('config.appsecret');
        $get_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
        $return_data = curlGet($get_access_token_url);
        if ($return_data['errcode']) {
            throw new Exception($return_data['errmsg'], $return_data['errcode']);
        }
        $access_token = $return_data['access_token'];
        $openid = $return_data['openid'];
        $get_userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}";
        $userinfo_data = curlGet($get_userinfo_url);
        if ($userinfo_data['errcode']) {
            throw new Exception($userinfo_data['errmsg'], $userinfo_data['errcode']);
        }
        return $userinfo_data;
    }

    /**
     * 登录操作
     * @return array
     */
    public function doLogin()
    {
        $return = [
            'status' => 1,
        ];
        $userinfo = $this->wechatAuth();
        $unionid = $userinfo['unionid'];
        $db_userinfo = $this->getInfoByField('unionid', $unionid);
        $UserLoginLogModel = new UserLoginLog();
        if (!$db_userinfo) {
            //新增用户
            $add_userinfo['nick_name'] = $userinfo['nickname'] ? $userinfo['nickname'] : '暂无昵称';
            $add_userinfo['head_img'] = $userinfo['headimgurl'];
            $add_userinfo['openid'] = $userinfo['openid'];
            $add_userinfo['unionid'] = $userinfo['unionid'];
            $add_userinfo['create_time'] = time();
            $add_userinfo['status'] = 2;
            $user_id = $this->insertGetId($add_userinfo);
            Session::set('cps_user_id', $user_id);
            Session::set('cps_user_name', $add_userinfo['nick_name']);
            Session::set('cps_user_status', $add_userinfo['status']);
            Session::set('cps_user_head_img', $add_userinfo['head_img']);
            Session::set('cps_user_mobile', $add_userinfo['mobile']);
            $UserLoginLogModel->writeLog($user_id); //记录登录日志
        } elseif (!$db_userinfo['status'] == 4) {
            $return['status'] = 0;
            $return['msg'] = '该账号已被冻结';
            return $return;
        } elseif ($db_userinfo['is_del'] == 1) {
            $return['status'] = 0;
            $return['msg'] = '该账号已被删除';
            return $return;
        } else {
            //更新昵称和头像
            $this->where([
                'id' => $db_userinfo['id']
            ])->update([
                'nick_name' => $userinfo['nickname'],
                'head_img'  => $userinfo['headimgurl']
            ]);
            Session::set('cps_user_id', $db_userinfo['id']);
            Session::set('cps_user_name', $db_userinfo['nick_name']);
            Session::set('cps_user_status', $db_userinfo['status']);
            Session::set('cps_user_head_img', $db_userinfo['head_img']);
            Session::set('cps_user_mobile', $db_userinfo['mobile']);
            $UserLoginLogModel->writeLog($db_userinfo['id']); //记录登录日志
        }
        return $return;
    }
    /**
     * 根据单字段获取信息
     * @param $user_name
     * @param string $fields
     * @return object
     */
    public function getInfoByField($field_name, $field_value, $fields = '*')
    {
        return $this->where($field_name, $field_value)->field($fields)->find();
    }

    /**
     * 发送短信验证码
     * @param $mobile
     * @return array
     */
    public function send_code($mobile)
    {
        $return = [
            'status' => 1,
        ];
        $mobileSendModel = new MobileSend();
        //获取最新的一次发送记录
        $send_data = $mobileSendModel->getInfoByField('mobile', $mobile);
        if ($send_data) {
            if ((time() - $send_data['send_time']) < 5*60) {
                $return['status'] = 0;
                $return['msg'] = '发送太频繁,请稍后再试';
                return $return;
            }
        }
        $code = createString(4);    //生成四位随机数字
        if (!$mobileSendModel->addData($mobile, $code)) {
            trace('添加短信发送记录失败:'.$mobileSendModel->getLastSql(), 'business');
            $return['status'] = 0;
            $return['msg'] = '发送太频繁,请稍后再试';
        }
        return $return;
    }

    /**
     * 当前用户绑定手机号
     * @param $user_name
     * @param $mobile
     * @return bool
     */
    public function bindMobile($user_name, $mobile)
    {
        $state = $this->where('id', Session::get('cps_user_id'))->update([
            'user_name' => $user_name,
            'mobile' => $mobile
        ]);
        if ($state) {
            Session::set('cps_user_mobile', $mobile);
        }
        return $state;
    }
}